﻿using Goooodbye.Core.Services;
using Goooodbye.Presentation.WinFormsApp.Properties;
using System;
using System.ComponentModel;
using System.IO;
using System.Windows.Forms;

namespace Goooodbye.Presentation.WinFormsApp
{
    public partial class FormDictionaryImport : FormBase
    {
        private readonly IDictService dictService;
        private readonly IImportService dictImportService;

        public FormDictionaryImport(IDictService dictService, IImportService dictImportService)
        {
            InitializeComponent();
            this.dictService = dictService;
            this.dictImportService = dictImportService;
        }

        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            try
            {
                var file = new FileInfo(this.txtFileName.Text);
                var append = this.radioAppend.Checked;
                var affected = dictImportService.Import(file, append);
                e.Result = new { ok = true, msg = $"导入完成. ({affected} 条)" };
            }
            catch (Exception ex)
            {
                e.Result = new { ok = false, msg = ex.Message };
            }
        }

        private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            this.progressBar1.Visible = false;
            dynamic res = e.Result;
            MessageBox.Show($"{res.msg}", "导入", MessageBoxButtons.OK, res.ok ? MessageBoxIcon.Information : MessageBoxIcon.Error);
            this.DialogResult = res.ok ? DialogResult.OK : DialogResult.None;
        }

        private void btnOpen_Click(object sender, EventArgs e)
        {
            this.openFileDialog1.Filter = Settings.Default.DefaultExt == "csv"
                ? "CSV UTF-8（逗号分隔）|*.csv"
                : "文本文件（逗号分隔）|*.txt";
            if (this.openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                this.txtFileName.Text = this.openFileDialog1.FileName;
            }
        }

        private void btnConfirm_Click(object sender, EventArgs e)
        {
            try
            {
                if (!String.IsNullOrEmpty(this.txtFileName.Text))
                {
                    this.progressBar1.Visible = true;
                    this.backgroundWorker1.RunWorkerAsync(this.txtFileName.Text);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
    }
}
